<template>
  <el-dialog v-loading="loading" center title="ئۇچۇرلار" :visible.sync="dialogVisible" width="60%" :before-close="dialogBeforeClose" :destroy-on-close="true">
    <el-form ref="form" :model="form" label-width="120px">
      <el-form-item label="ئىسمى:" prop="title">
        <el-row>
          <el-col :span="12">
            <el-input size="small" v-model="form.title" autocomplete="off"></el-input>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="رەسىمى:" prop="coverImg">
        <!-- <img :src="info.coverImg" style="height:200px" alt=""> -->
        <el-upload class="avatar-uploader" action="" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
          <img v-if="form.coverImg" :src="form.coverImg" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <!-- <el-button type="primary" v-if="imgFile">رەسىم ئادىرىسگە ئېرىشىش</el-button> -->
      </el-form-item>
      <el-form-item label="VID:" prop="vid">
        <span style="font-size:24px">{{form.vid}}</span>
      </el-form-item>
      <el-form-item label="جەمئىي قىسىم:" prop="total_qisim">
        <el-row>
          <el-col :span="4">
            <el-input size="small" v-model="form.total_qisim" autocomplete="off"></el-input>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="تىپى:" prop="type">
        <el-row>
          <el-col :span="12">
            <el-select size="small" v-model="form.type" placeholder="">
              <el-option v-for="item in [{label:'كىنو فىلىم',value:1},{label:'كۆپ قىسىملىق',value:2}]" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="تۈرى:" prop="sort">
        <el-row>
          <el-select multiple size="small" v-model="form.sort" placeholder="">
            <el-option v-for="item in sortList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-row>
      </el-form-item>
      <el-form-item label="تەۋە دۆلەت:" prop="nation">
        <el-row>
          <el-col :span="12">
            <el-select size="small" v-model="form.nation" placeholder="">
              <el-option v-for="item in nationList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label=" تىل:" prop="lang">
        <el-row>
          <el-col :span="12">
            <el-select size="small" v-model="form.lang" placeholder="">
              <el-option v-for="item in langList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="قىسىملىرى：" prop="list">
        <el-table stripe :data="form.list" style="max-height:50vh;overflow-y:scroll">
          <el-table-column align="center" prop="qisim" label="قىسىمى" width="80px">
            <template slot-scope="{row}">
              <el-input v-model="row.qisim" size="small" placeholder=""></el-input>
            </template>
          </el-table-column>
          <!-- <el-table-column align="center" prop="id" label="ID" width="80px"></el-table-column> -->
          <!-- <el-table-column align="center" prop="vid" label="VID"></el-table-column> -->
          <el-table-column align="center" width="250px" prop="url" label="كىنو ئادىرىسى">
            <template slot-scope="{row}">
              <el-input v-model="row.url" size="small" placeholder=""></el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="create_time" label="ۋاقتى" width="155px">
            <template slot-scope="{row}">
              {{row.create_time ? $dayjs(row.create_time).format('YYYY-MM-DD HH:mm:ss') : ''}}
            </template>
          </el-table-column>
          <el-table-column align="center" prop="url_type" label="ئادىرىس تىپى" width="170px">
            <template slot-scope="{row}">
              <el-select size="small" v-model="row.url_type" placeholder="">
                <el-option v-for="item in [
                      {label:'نورمال ئادىرىس',value:1},
                      {label:'تېڭشۈن wxv',value:2},]" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column align="center" label="مەشغۇلات">
            <template slot-scope="{row,$index}">
              <el-button type="primary" size="small" @click="playVideo(row)">قويۇش</el-button>
              <el-button type="danger" v-if="row.id" @click="removeCurrQisim(row,$index)" size="small">سانداندىن يۇيۇش</el-button>
              <el-button type="danger" size="small" v-if="form.list.length!=1" @click="delCurrLine($index)">يۇيۇش</el-button>
              <el-button size="small" v-if="$index==form.list.length-1" @click="createNewLine" type="primary" icon="el-icon-circle-plus-outline"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label-width="0">
        <el-row style="margin-top:24px;text-align:center">
          <el-button type="primary" @click="saveQisimList">قىسىمنى ساقلاش</el-button>
        </el-row>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="dialogVisible = false">ئەمەلدىن قالدۇرۇش</el-button>
      <el-button type="primary" @click="saveVideoInfo">كىنو ئۇچۇرنى ساقلاش</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { deleteQisim, updaQisimInfo, updateVideoInfo } from '@/api/kino';
/**
 * 深度判断两个对象是否相同
 */
function diff(obj1, obj2) {
  const keys1 = Object.keys(obj1);
  const keys2 = Object.keys(obj2);

  if (keys1.length !== keys2.length) {
    return false;
  }
  else {
    for (let key in obj1) {
      if (!obj2.hasOwnProperty(key)) {
        return false;
      }
      //类型相同
      if (typeof obj1[key] === typeof obj2[key]) {
        //同为引用类型
        if (typeof obj1[key] === 'object' && typeof obj2[key] === 'object') {
          const equal = diff(obj1[key], obj2[key]);
          if (!equal) {
            return false;
          }
        }
        //同为基础数据类型
        if (typeof obj1[key] !== 'object' && typeof obj2[key] !== 'object' && obj1[key] !== obj2[key]) {
          return false;
        }
      }
      else {
        return false;
      }
    }
  }
  return true;
}
import { LANG_MAP, NATION_MAP } from '@/utils/enums'

export default {
  name: 'EditDialog',
  props: {
    info: {
      type: Object,
      default: () => { }
    },
    sortList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      form: {},
      dialogVisible: false,
      loading: false,
      nationMap: NATION_MAP,
      nationList: Object.keys(NATION_MAP).reduce((list, curr) => list.concat({ label: NATION_MAP[curr], value: Number(curr) }), []),
      imgFile: null,
      langList: Object.keys(LANG_MAP).reduce((list, curr) => list.concat({ label: LANG_MAP[curr], value: Number(curr) }), [])
    };
  },
  /* created() {

  },
  mounted() {

  }, */
  methods: {
    dialogBeforeClose(done) {
      //   console.log(diff(this.form, this.info));
      done()
    },
    playVideo(row) {
      let url;
      if (row.url_type == 1) {
        url = row.url
      } else if (row.url_type == 2) {
        // url = `https://mp.weixin.qq.com/mp/videoplayer?action=get_mp_video_play_url&preview=0&__biz=&mid=&idx=&vid=${row.url}&uin=&key=&pass_ticket=&wxtoken=&appmsg_token=&x5=0&f=json` //获取地址
        url = `https://mp.weixin.qq.com/mp/readtemplate?t=pages/video_player_tmpl&action=mpvideo&auto=0&vid=${row.url}`
      }
      window.open(url, '_blank')
      //   console.log(row);
    },
    async saveVideoInfo() {
      let { vid, title, coverImg, lang, sort, type, total_qisim, nation } = this.form;
      if (!coverImg) {
        this.$message.warning('رەسىم چىقىرىڭ')
        return
      }
      if (this.imgFile && this.info.coverImg == coverImg) {
        coverImg = await this.uploadImg()
      }
      let info = {
        vid,
        title: this.info.title == title ? null : title,
        coverImg: this.info.coverImg == this.form.coverImg ? null : coverImg,
        total_qisim: this.info.total_qisim == total_qisim ? null : Number(total_qisim),
        sort: JSON.stringify(this.info.sort) == JSON.stringify(sort) ? null : JSON.stringify(sort),
        type: this.info.type == type ? null : Number(type),
        lang: this.info.lang == lang ? null : Number(lang),
        nation: this.info.nation == nation ? null : Number(nation),
      };
      console.log(info);
      let keyCount = Object.keys(info).reduce((count, key) => count + (info[key] != null ? 1 : 0), 0);
      if (keyCount == 1) {
        this.$message.warning('سىز ھېچقايسى تۈرنى ئۆزگەرتمەپسىز')
        return
      }
      this.$confirm('ساقلاشنى جەزملەشتۈرەمسىز؟', {
        cancelButtonText: 'ياق',
        confirmButtonText: 'ھەئە'
      }).then(_ => {
        this.loading = true
        updateVideoInfo(info).then(res => {
          if (res.affectedRows) {
            this.$message.success('ساقلاندى');
            this.$emit('getList');
          }
          this.loading = false
        }).catch(err => {
          this.loading = false
        })
        // console.log(info);
      }).catch(_ => { })
    },
    uploadImg() {
      return new Promise((resolve, reject) => {
        var cos = new COS({
          SecretId: 'AKID1sTnqc8MJ0QedLnysUqvjGWWFgtqZ2D8',
          SecretKey: 'f28yXppZ3GDsHSMzMSIsBDySeaEbhW5N',
        });
        let self = this;
        this.$loading();
        cos.putObject({
          Bucket: 'qaplan-1252253374', /* 必须 */
          Region: 'ap-shanghai',     /* 存储桶所在地域，必须字段 */
          Key: `/AppImg/${this.$store.state.user.name || 'Yusup'}/` + Date.now().toString(36) + (Math.random().toString().slice(2, 10) * 1000).toString(32) + '.jpg',              /* 必须 */
          StorageClass: 'STANDARD',
          Body: this.imgFile, // 上传文件对象
          onProgress: function (progressData) {
            console.log(JSON.stringify(progressData));
          }
        }, function (err, data) {
          self.$loading().close();
          if (err) {
            self.$message.error(err);
            reject();
          } else {
            if (data.statusCode == 200) {
              let imgUrl = data.Location.replace('qaplan-1252253374.cos.ap-shanghai.myqcloud.com', 'https://cdn.qolayapp.cn')
              self.$set(self.form, 'coverImg', imgUrl)
              // self.form.coverImg = data.Location.replace('qaplan-1252253374.cos.ap-shanghai.myqcloud.com', 'https://cdn.qolayapp.cn')
              self.$message.success('رەسىم چىقىرىلدى')
              resolve(imgUrl)
            } else {
              reject
            }
          }
          // console.log(err || data);
        });
      })
    },
    beforeAvatarUpload(file, ...args) {
      this.imgFile = file;
      return false
    },
    handleAvatarSuccess() {
      console.log(...arguments);
    },
    delCurrLine(index) {
      this.form.list.splice(index, 1)
    },
    createNewLine() {
      this.form.list.push({ qisim: this.form.list.length + 1, url_type: 1 })
    },
    saveQisimList() {
      let qisimList = this.form.list;
      for (let [index, item] of qisimList.entries()) {
        if (!item.qisim || !item.url_type || !item.url) {
          this.$message.error(`${index + 1} -قۇرنى تۇللۇق كىرگۈزمەپسىز`);
          return;
        } else {
          item.qisim = Number(item.qisim);
          item.url_type = Number(item.url_type);
        }
      }
      updaQisimInfo({ vid: this.info.vid, list: qisimList }).then(res => {
        this.$message.success('ساقلاندى')
      }).catch(err => {
        this.$message.error(err)
      })
    },
    removeCurrQisim(row, index) {
      this.$confirm('سانداندىن يۇيۇشنى جەزملەشتۈرەمسىز؟', {
        cancelButtonText: 'ياق',
        confirmButtonText: 'ھەئە'
      }).then(_ => {
        console.log(row);
        // console.log(info);
        deleteQisim({ id: row.id }).then(res => {
          this.$message.success('مۇۋەپپەقىيەلىك يۇيۇلدى')
          this.form.list.splice(index, 1)
        }).catch(_ => { })
      }).catch(_ => { })
    }
  },
  watch: {
    info(value) {
      this.form = JSON.parse(JSON.stringify(value))
    },
    /* 'form.total_qisim': {
      handler(val) {
        if (this.form.list.length != val) {
          let diff = Math.abs(val - this.form.list.length);
          if (this.form.list.length < val) {
            for (let i = 0; i < diff; i++) {
              this.form.list.push({ qisim: this.form.list.length + 1, url_type: 1 })
            }
          } else {
            this.form.list.splice(val, diff)
          }
        }
      }
    } */
  }
};
</script>

<style scoped lang="scss">
</style>
